const reqlib = require('app-root-path').require
const pug = require('pug')
const localConfig = reqlib('/config')
const emailConfig = localConfig.email

const sender = emailConfig.senderAccount.auth.user
const formName = emailConfig.formName
const adminEmail = emailConfig.adminAccount.user

function renderEmail (file, data) {
  return pug.renderFile(`../emailTemplate/${file}.pug`, data || {})
}

const sayHello = (option) => {
  return {
    // 格式 name<mail>,发件人的名字<邮箱>
    from: `"${formName}" <${sender}>`,
    // 发送的
    to: option.userEmail || adminEmail,
    // 标题
    subject: 'hello world',
    // html
    html: renderEmail('sayHello')
  }
}

const sendErrorEmail = (option) => {
  return {
    // 格式 name<mail>,发件人的名字<邮箱>
    from: `"${formName}" <${sender}>`,
    // 发送的
    to: option.userEmail || adminEmail,
    // 标题
    subject: '错误',
    // html
    html: `${JSON.stringify({ message: option.err.message, stack: option.err.stack })}`
  }
}

const sendBtbTrChange = (option) => {
  option = option || {}
  const changeList = option.changeList || []
  let t = ''
  changeList.forEach((v) => {
    t += `<li>${v.name}(${v.code})：转变为${v.tr > 0 ? '<span style="color: red">上升</span>' : '<span style="color: green">下降</span>'}</li>`
  })
  return {
    // 格式 name<mail>,发件人的名字<邮箱>
    from: `"${formName}" <${sender}>`,
    // 发送的
    to: option.userEmail || adminEmail,
    // 标题
    subject: '货币趋势改变',
    // html
    html: `<div><ul>${t}</ul></div>`
  }
}

const sendBtbAbnormalVolatility = (option) => {
  option = option || {}
  const list = option.list || []
  let t = ''
  list.forEach((v) => {
    const val = v.priceChangePercent > 0 ? `<span style="color: red">${v.priceChangePercent}%</span>` : `<span style="color: green">${v.priceChangePercent}%</span>`
    t += `<li>${v.code}-${v.type}级别异动：${val}</li>`
  })
  return {
    // 格式 name<mail>,发件人的名字<邮箱>
    from: `"${formName}" <${sender}>`,
    // 发送的
    to: option.userEmail || adminEmail,
    // 标题
    subject: '货币异常波动',
    // html
    html: `<div><ul>${t}</ul></div>`
  }
}

module.exports = {
  sayHello,
  sendErrorEmail,
  sendBtbTrChange,
  sendBtbAbnormalVolatility
}
